package com.example.ktapplication.adapter

import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.R
import com.example.ktapplication.bean.MessageBean
import com.example.ktapplication.databinding.RvMessageItemLayoutBinding

class MessageAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {


    private val links by lazy {
        mutableListOf<MessageBean>()
    }

    var itemCallBack: OnItemClickListener? = null

    @SuppressLint("NotifyDataSetChanged")
    fun addData(data: MutableList<MessageBean>) {
        links.clear()
        links.addAll(data)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.rv_message_item_layout, parent, false)
        return MessageViewHolder(view)
    }


    override fun getItemCount(): Int {
        return links.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        if (holder is MessageViewHolder) {
            val msItem = links[position]
            holder.binding.llItem.setOnClickListener(View.OnClickListener {
                itemCallBack?.onItemClick(msItem)
            })
            holder.binding.tvName.text=msItem.name
            holder.binding.tvNumber.text=msItem.number
            Glide.with(AppGlobals.getApplication())
                .load(R.mipmap.icon_mine)
                .apply(RequestOptions.circleCropTransform())
                .into(holder.binding.ivHeader)
        }
    }

    inner class MessageViewHolder(item: View) : RecyclerView.ViewHolder(item) {
        val binding by lazy {
            RvMessageItemLayoutBinding.bind(item)
        }
    }

    interface OnItemClickListener {
        fun onItemClick(bean: MessageBean)
    }
}